package cn.itcast.service;

import cn.itcast.properties.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc:
 * @author: panxiyi
 * @date: 2023/5/21 8:51 下午
 */
public class IpCountService {

    private Map<String, Integer> ipCountMap = new HashMap<>();

    @Autowired
    // 当前的request对象注入工作由使用当前starter的工程自动装配
    private HttpServletRequest httpServletRequest;

    public void count() {

        String ip = httpServletRequest.getRemoteAddr();
        System.out.println("-------------------------" + ip);
        Integer curCnt = ipCountMap.get(ip);
        if (curCnt == null) {
            ipCountMap.put(ip,  1);
        } else {
            ipCountMap.put(ip, curCnt + 1);
        }
    }

    @Autowired
    private IpProperties ipProperties;

    @Scheduled(cron = "0/#{ipProperties.cycle} * * * * ?")
    public void print() {
        System.out.println("        IP访问监控  ");
        if (ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())) {
            System.out.println("+-----ip-address-----+--num--+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.println(String.format("|%18s  |%5d  |", key, value));
            }
            System.out.println("+--------------------+-------+");
        } else if (ipProperties.getModel().equals(IpProperties.LogModel.SIMPLE.getValue())) {
            System.out.println("+-----ip-address-----+");
            for (String key : ipCountMap.keySet()) {
                System.out.println(String.format("|%18s  |", key));
            }
            System.out.println("+--------------------+");
        }


        if (ipProperties.getCycleReset()) {
            ipCountMap.clear();
        }
    }

    public static void main(String[] args) {
        new IpCountService().print();
    }
}
